from PySide6.QtWidgets import QWidget,QMessageBox,QTableWidgetItem,QHeaderView,QMenu,QAbstractItemView
from sqlalchemy.orm import Session
from PySide6.QtCore import Qt

from views.person.work.jobinfo import Ui_jobinfo
from views.person.model.person import PersonBaseInfo,JobInfo
from settings.publicFuncation.exceldownloadimport import OperationModel
from settings.publicvar import engine

from views.person.work.opetrationjobView import OperationJobInfoView

import pandas as pd
class JobInfoView(QWidget,Ui_jobinfo):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.jobtable.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.jobtable.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.jobtable.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)
        self.jobtable.setContextMenuPolicy(Qt.CustomContextMenu)
        self.jobtable.customContextMenuRequested.connect(self.generate_menu)

        self.downloadmodle.clicked.connect(self.downloadmodleFun)
        self.importbtn.clicked.connect(self.importdataFun)
        self.addjobinfo.clicked.connect(self.saveFun)
        self.sereachedit.editingFinished.connect(self.serearchFun)
        self.serearchbtn.clicked.connect(self.serearchFun)

        self.loadTableData()
    # 模板下载
    def downloadmodleFun(self):
        OperationModel().downloadmodleFun('工作信息模板.xlsx')

    # 数据导入
    def importdataFun(self):
        names = ['idx','name','IDcard','enter_unit','transfer_out_unit','enter_date','transfer_out_date',
                 'enter_exit_mode','employment_status','employment_type','mark']
        dtype = {'IDcard': str}
        parse_dates = ['enter_date', 'transfer_out_date']
        data = OperationModel().importdataFun(names,dtype,parse_dates)
        data['enter_date'] = data['enter_date'].replace({pd.NaT: None})
        data['transfer_out_date'] = data['transfer_out_date'].replace({pd.NaT: None})
        with Session(engine) as session,session.begin():
            exist_personbase = session.query(PersonBaseInfo.IDcard,PersonBaseInfo.id).filter(
                PersonBaseInfo.IDcard.in_(data.IDcard.to_list())).all()
            exist_IDcard = [item[0] for item in exist_personbase]
            exist_personbase = pd.DataFrame(exist_personbase).rename(columns={'id': 'name_id'})
            save_job = data[data['IDcard'].isin(exist_IDcard)]
            save_job = pd.merge(exist_personbase, save_job, on='IDcard').drop(
                    columns=['name', 'IDcard']).to_dict('records')
            jobs = []
            for job in save_job:
                jobs.append(JobInfo(**job))
            session.add_all(jobs)
            QMessageBox.information(None,'成功','共%s条，成功%s条,失败%s条'%(len(data),len(jobs),len(data)-len(jobs)))
        self.loadTableData()

    #表结构
    def setTableStructure(self, data):
        self.jobtable.setRowCount(len(data))
        for i,item in enumerate(data):
            idx = QTableWidgetItem(str(item.id))
            self.jobtable.setItem(i,0,idx)
            try:
                name = QTableWidgetItem(item.personinfo.name)
            except:
                name = QTableWidgetItem('')
            self.jobtable.setItem(i, 1, name)
            enter_unit = QTableWidgetItem(str(item.enter_unit))
            self.jobtable.setItem(i,2,enter_unit)
            transfer_out_unit = QTableWidgetItem(str(item.transfer_out_unit))
            self.jobtable.setItem(i, 3, transfer_out_unit)
            enter_date = QTableWidgetItem(str(item.enter_date))
            self.jobtable.setItem(i,4,enter_date)
            transfer_out_date = QTableWidgetItem(str(item.transfer_out_date))
            self.jobtable.setItem(i,5,transfer_out_date)
            enter_exit_mode = QTableWidgetItem(item.enter_exit_mode)
            self.jobtable.setItem(i,6,enter_exit_mode)
            employment_status = QTableWidgetItem(item.employment_status)
            self.jobtable.setItem(i,7,employment_status)
            employment_type = QTableWidgetItem(item.employment_type)
            self.jobtable.setItem(i,8,employment_type)
            mark = QTableWidgetItem(item.mark)
            self.jobtable.setItem(i,9,mark)

    # 表格数据加载
    def loadTableData(self):
        with Session(engine) as session,session.begin():
            jobinfos = session.query(JobInfo).all()
            self.setTableStructure(jobinfos)

    # 菜单数据
    def generate_menu(self,pos):
        menu = QMenu()
        viewitem = menu.addAction('查看')
        changeitem = menu.addAction('修改')
        deletitem = menu.addAction('删除')
        action = menu.exec(self.jobtable.mapToGlobal(pos))
        posrow = self.jobtable.currentRow()
        columns = self.jobtable.columnCount()
        data = [self.jobtable.item(posrow, i).text() for i in range(columns)]
        if action == changeitem:
            learningexperience = OperationJobInfoView('change',data)
            learningexperience.exec()
            pass
        elif action == deletitem:
            learningexperience = OperationJobInfoView('delete',data)
            learningexperience.exec()
        elif action == viewitem:
            learningexperience = OperationJobInfoView('view', data)
            learningexperience.exec()
            pass
        self.loadTableData()

    # 添加
    def saveFun(self):
        save_job = OperationJobInfoView('add', False)
        save_job.exec()

        # 搜索框数据处理

    def serearchFun(self):
        sereachdata = self.sereachedit.text().strip()
        if sereachdata == '':
            QMessageBox.critical(None, '错误', '搜索框不能为空！')
            self.loadTableData()
        else:
            with Session(engine) as session, session.begin():
                sereachName = session.query(PersonBaseInfo).filter(
                    PersonBaseInfo.name.like('%' + sereachdata + '%')).all()
                sereachIDcard = session.query(PersonBaseInfo).filter(
                    PersonBaseInfo.IDcard.like('%' + sereachdata + '%')).all()
                sereachiphone = session.query(PersonBaseInfo).filter(
                    PersonBaseInfo.iphone.like('%' + sereachdata + '%')).all()
                sereachData = sereachName + sereachIDcard + sereachiphone
                jobs = []
                if sereachData:
                    for personbase in sereachData:
                        for job in personbase.jobinfos:
                            jobs.append(job)
                else:
                    QMessageBox.critical(None, '没有数据', '你搜索数据不存在！')
                self.setTableStructure(jobs)
